<template>
  <div :class="{ fullscreen: fullscreen }" class="tinymce-container" :style="{ width: containerWidth }">
    <textarea :id="tinymceId" class="tinymce-textarea" />
    <!-- <div class="editor-custom-btn-container">
      <editorImage color="#1890ff" class="editor-upload-btn" @successCBK="imageSuccessCBK" />
    </div> -->
  </div>
</template>

<script>
/**
 * docs:
 * https://panjiachen.github.io/vue-element-admin-site/feature/component/rich-editor.html#tinymce
 */
import editorImage from "./components/EditorImage";
import plugins from "./plugins";
import toolbar from "./toolbar";
import load from "./dynamicLoadScript";
// import UploadJs from "@/commonJs/upload.js";
import { getOssData, sendOssData } from '@/api/common'
// why use this cdn, detail see https://github.com/PanJiaChen/tinymce-all-in-one
const tinymceCDN =
  "https://cdn.jsdelivr.net/npm/tinymce-all-in-one@4.9.3/tinymce.min.js";

export default {
  name: "Tinymce",
  components: { editorImage },
  props: {
    id: {
      type: String,
      default: function () {
        return (
          "vue-tinymce-" +
          +new Date() +
          ((Math.random() * 1000).toFixed(0) + "")
        );
      },
    },
    value: {
      type: String,
      default: "",
    },
    toolbar: {
      type: Array,
      required: false,
      default() {
        return [];
      },
    },
    menubar: {
      type: String,
      default: "file edit insert view format table",
    },
    height: {
      type: [Number, String],
      required: false,
      default: 360,
    },
    width: {
      type: [Number, String],
      required: false,
      default: "auto",
    },
  },
  data() {
    return {
      // UploadJs, // 下载文件的公共方法
      hasChange: false,
      hasInit: false,
      tinymceId: this.id,
      fullscreen: false,
      languageTypeList: {
        zh: "zh_CN",
      },
    };
  },
  computed: {
    language() {
      // 'zh'处本来是this.$store.getters.language,本地化处理
      return this.languageTypeList["zh"];
    },
    containerWidth() {
      const width = this.width;
      if (/^[\d]+(\.[\d]+)?$/.test(width)) {
        // matches `100`, `'100'`
        return `${width}px`;
      }
      return width;
    },
  },
  watch: {
    value(val) {
      if (!this.hasChange && this.hasInit) {
        this.$nextTick(() =>
          window.tinymce.get(this.tinymceId).setContent(val || "")
        );
      }
    },
    language() {
      this.destroyTinymce();
      this.$nextTick(() => this.initTinymce());
    },
  },
  mounted() {
    this.init();
  },
  activated() {
    if (window.tinymce) {
      this.initTinymce();
    }
  },
  deactivated() {
    this.destroyTinymce();
  },
  destroyed() {
    this.destroyTinymce();
  },
  methods: {
    init() {
      // 2022/05/17不使用cdn加载，改成在index.html引入整个包
      // dynamic load tinymce from cdn
      // load(tinymceCDN, (err) => {
      //   if (err) {
      //     this.$message.error(err.message);
      //     return;
      //   }

      this.initTinymce();

      // });
    },
    initTinymce() {
      const _this = this;
      window.tinymce.init({
        content_style: "img {max-width:100%;}",
        image_dimensions: true, //插入图片显示宽高
        language: this.language,
        selector: `#${this.tinymceId}`,
        width: this.width,
        height: this.height,
        body_class: "panel-body ",
        object_resizing: false,
        toolbar: this.toolbar.length > 0 ? this.toolbar : toolbar,
        menubar: this.menubar,
        plugins: plugins,
        fontsize_formats: "8pt 10pt 12pt 14pt 18pt 24pt 36pt",
        end_container_on_empty_block: true,
        powerpaste_word_import: "clean",
        code_dialog_height: 450,
        code_dialog_width: 1000,
        advlist_bullet_styles: "square",
        advlist_number_styles: "default",
        imagetools_cors_hosts: ["www.tinymce.com", "codepen.io"],
        default_link_target: "_blank",
        link_title: false,
        nonbreaking_force_tab: true, // inserting nonbreaking space &nbsp; need Nonbreaking Space Plugin
        images_upload_url: "",
        init_instance_callback: (editor) => {
          if (_this.value) {
            editor.setContent(_this.value);
          }
          _this.hasInit = true;
          editor.on("NodeChange Change KeyUp SetContent", () => {
            this.hasChange = true;
            this.$emit("input", editor.getContent());
          });
        },
        // 图片上传：
        images_upload_handler: function (blobInfo, success, failure, progress) {
          const file = blobInfo.blob();
          // const form = new FormData();
          // form.append("myFile", file);
          // uploadImg(form).then((res) => {
          //   console.log(res);
          //   succFun(res.data.data.fileUrl);
          // });
          //新上传文件方法OSS
          _this.uploadFile(file, (url) => {
            ;
            success(_this.pictureHandle(url, 'pc_zoom_small'))
          })
          // UploadJs.uploadFn(file, (url) => {
          //   success(url);
          // });
        },
        setup(editor) {
          editor.on("FullscreenStateChanged", (e) => {
            _this.fullscreen = e.state;
          });
        },

        convert_urls: false,
      });
    },
    async uploadFile(file, cb) {
      // 生成文件名，作为 key 使用
      const generateFileName = (ossData, file) => {
        const suffix = file.name.slice(file.name.lastIndexOf('.'))
        const filename = Date.now() + suffix
        return ossData.dir + filename
      }
      const ossData = await getOssData()
      const key = generateFileName(ossData, file)
      const formdata = new FormData()
      // 注意参数的顺序，key 必须是第一位，表示OSS存储文件的路径
      formdata.append('key', key)
      formdata.append('OSSAccessKeyId', ossData.accessId)
      formdata.append('policy', ossData.policy)
      formdata.append('signature', ossData.signature)
      // 文件上传成功默认返回 204 状态码，可根据需要修改为 200
      formdata.append('success_action_status', '200')
      // file 必须放在最后一位
      formdata.append('file', file)
      const res = await sendOssData(ossData.host, formdata)
      if (res.status === 200) {
        cb(ossData.host + '/' + key)
      }
    },
    destroyTinymce() {
      const tinymce = window.tinymce.get(this.tinymceId);
      if (this.fullscreen) {
        tinymce.execCommand("mceFullScreen");
      }

      if (tinymce) {
        tinymce.destroy();
      }
    },
    setContent(value) {
      window.tinymce.get(this.tinymceId).setContent(value);
    },
    getContent() {
      window.tinymce.get(this.tinymceId).getContent();
    },
    imageSuccessCBK(arr) {
      console.log(arr);
      arr.forEach((v, index) => {
        let file = this.blobToFile(UploadJs.convertBase64UrlToBlob(v.url), v);
        console.log(file);
        UploadJs.uploadFn(
          file,
          (res, size, data) => {
            console.log(res);
            if (v.uid == data.uid || v.name == data.name) {
              v.url = res;
            }
            if (index == arr.length - 1) {
              this.showPic(arr);
            }
          },
          null,
          v
        );
      });
    },
    showPic(arr) {
      arr.forEach((v) => {
        window.tinymce
          .get(this.tinymceId)
          .insertContent(`<img class="wscnph" src="${v.url}" >`);
      });
    },
    /**
     * @function 将blob转换为file格式
     */
    blobToFile(blob, curr) {
      console.log(curr.uid);
      if (curr.name) {
        return new window.File([blob], curr.name, {
          type: blob.type,
        });
      } else {
        return new window.File([blob], Date.parse(new Date()) + ".jpg", {
          type: blob.type,
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.tinymce-container {
  position: relative;
  line-height: normal;
}

.tinymce-container {
  ::v-deep {
    .mce-fullscreen {
      z-index: 10000;
    }
  }
}

.tinymce-textarea {
  z-index: -1;
  visibility: hidden;
}

.editor-custom-btn-container {
  position: absolute;
  top: 4px;
  right: 4px;
  /*z-index: 2005;*/
}

.fullscreen .editor-custom-btn-container {
  position: fixed;
  z-index: 10000;
}

.editor-upload-btn {
  display: inline-block;
}
</style>


